package parkshop.pmcourse.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import parkshop.pmcourse.domain.FavoriteProduct;
import parkshop.pmcourse.domain.FavoriteSaller;
import parkshop.pmcourse.domain.Orders;
import parkshop.pmcourse.domain.Product;
import parkshop.pmcourse.domain.ShoppingCart;
import parkshop.pmcourse.dto.PageBean;
import parkshop.pmcourse.dto.User;
import parkshop.pmcourse.service.CustomerService;
import parkshop.pmcourse.service.FavoriteService;
import parkshop.pmcourse.service.ProductService;
import parkshop.pmcourse.service.ShoppingCartService;
import parkshop.pmcourse.utils.ConstantUtil;


@Controller
@RequestMapping("/customer")
public class CustomerCtrl {
	
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private ShoppingCartService shoppingCartService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private FavoriteService favoriteService;
		

	/*
	 * cart
	 Search Product
	View Product Page
	Add Cart
	Add Favorite
	Add Favorite Shop or Product 
	Add cart
	Delete Product from Cart
	Modify Product Quantity

	 */
	// customer add goods into their own shop cart
	@PostMapping("/cart/add")
    public void addGoodsIntoCart(Long productId,int quantity,HttpServletRequest request, HttpServletResponse response, Model model, HttpSession httpSession) {
		User customer = (User) httpSession.getAttribute(ConstantUtil.nameOfCurUser);
		if (customer == null) {
			try {
				response.getWriter().write("please signin first");
				return;
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			ShoppingCart shoppingCart = new ShoppingCart();
			shoppingCart.setCustomerId(customer.getId());
			shoppingCart.setProductId(productId);
			shoppingCart.setStatus(ConstantUtil.addedIntoCart);
			shoppingCart.setQuantity(quantity);
			shoppingCartService.saveShoppingCart(shoppingCart);
			try {
				response.getWriter().write("success");
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}
		}
		
	}
	@GetMapping("/cart/remove/{cartId}")
	public String removeGoodsFormCart(@PathVariable int cartId,HttpServletRequest request, Model model) {
		
		shoppingCartService.deleteShopCartById((long) cartId);
		
		return "redirect:/customer/shoppingcart/list/1";
	}
	// balance(结算购物车) their cart
	@GetMapping("/cart/payment/{cartId}")
	public String payingCart(@PathVariable int cartId,HttpServletRequest request, Model model) {

		ShoppingCart cart=shoppingCartService.getShoppingCartByCartId((long) cartId);
		model.addAttribute("product", productService.getProductById(cart.getProductId()));
		model.addAttribute("orders", cartToOrders(cart));
		return "customer/needPayment";
	}
	/*
	 * 支付购物车成功将产生一个订单记录
	 */
	private Orders cartToOrders(ShoppingCart cart){
		Product product=productService.getProductById(cart.getProductId());
		
		Orders order=new Orders();
		order.setOrderMoney(product.getPrice()*cart.getQuantity());
		order.setId(ConstantUtil.shoppingCartOrderId);// 如果订单的id 为 -1 表示购物车的订单，
		order.setShopId(cart.getId());// 传递购物车订单的 id,
		order.setCustomerId(cart.getCustomerId());
		order.setOrderTime(new Date());
		return order;
	}
	
	@GetMapping("/shoppingcart/list/{pageNumber}")
	public String listShoppingCart(@PathVariable int pageNumber,Model model,HttpSession session){
		User curUser=(User) session.getAttribute(ConstantUtil.nameOfCurUser);
		PageBean productPage=shoppingCartService.getProductPageByCustomerId(curUser.getId(), pageNumber);
		model.addAttribute("productPage",productPage);
		return "customer/shopCart";
	}
	
	/*
	 * Favorite
	 */
	@PostMapping("/favorite/product/add")
	public void addFavoriteProduct(Long productId, HttpServletResponse response, Model model, HttpSession httpSession) {
		User customer = (User) httpSession.getAttribute(ConstantUtil.nameOfCurUser);
		if (customer == null) {
			try {
				response.getWriter().write("please signin first");
				return;
			} catch (IOException e) {
			}
		} else {
			
			FavoriteProduct favorite=new FavoriteProduct();
			favorite.setCustomerId(customer.getId());
			favorite.setProductId(productId);
			boolean flag=favoriteService.saveFavoriteProduct(favorite);
			String message=flag?"success":"failed,product already in your favorite or others reasons";
			try {
				response.getWriter().write(message);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	@GetMapping("/favorite/list/{pageNumber}")
	public String listFavorites(@PathVariable int pageNumber,HttpSession session, Model model) {
		User user=(User) session.getAttribute(ConstantUtil.nameOfCurUser);
		PageBean productList=favoriteService.getFavoriteProductByCustomerId(pageNumber,user.getId());
		PageBean shopList=favoriteService.getFavoriteShopByCustomerId(pageNumber,user.getId());
		
		model.addAttribute("favoriteProductPage", productList);
		model.addAttribute("favoriteShopPage", shopList);
		return "customer/favorite";
	}
	@GetMapping("/favorite/product/remove/{favoriteProductId}")
	public String removeFavoriteProduct(@PathVariable Long favoriteProductId, HttpServletRequest request) {
		User user=(User) request.getSession().getAttribute(ConstantUtil.nameOfCurUser);
		favoriteService.deleteFavoriteProduct( favoriteProductId, user.getId());
		return "redirect:/customer/favorite/list/1";
	}
	@PostMapping("/favorite/shop/add")
	public void addFavoriteShop(Long shopId, HttpServletResponse response,Model model, HttpSession httpSession) {
		
		User customer = (User) httpSession.getAttribute(ConstantUtil.nameOfCurUser);
		if (customer == null) {
			try {
				response.getWriter().write("please signin first");
				return;
			} catch (IOException e) {
			}
		} else {
			
			FavoriteSaller favorite=new FavoriteSaller();
			favorite.setCustomerId(customer.getId());
			favorite.setShopId(shopId);
			boolean flag=favoriteService.saveFavoriteSaller(favorite);
			String message=flag?"success":"the shop already in your favorite or others reason result the failed";
			try {
				
				response.getWriter().write(message);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	@GetMapping("/favorite/shop/remove/{productId}")
	public String removeFavoriteShop(@PathVariable Long productId,HttpServletRequest request, Model model) {
		User user=(User) request.getSession().getAttribute(ConstantUtil.nameOfCurUser);
		favoriteService.deleteFavoriteSaller(productId, user.getId());
		return "redirect:/customer/favorite/list/1";
	}

	
	@GetMapping("/payment/need")
	public String showNeedPayment(HttpServletRequest request, Model model){
		
		return "customer/myshoppings";
	}
	

	@PostMapping("/shop/open")
	public String openShop(String shopName,HttpServletRequest request, Model model){
		
		HttpSession session=request.getSession(false);
		if(session!=null){
		User user=(User) session.getAttribute(ConstantUtil.nameOfCurUser);
		boolean flag=customerService.openShop(user, shopName);
		
		model.addAttribute(ConstantUtil.nameOfCurUser, user);
		model.addAttribute("message",flag?"open shop successful, waitting mall Admin approve":"open shop failed");
		 return "module/personInfo"; 
		}
		return "/login/customer";
	}
	/*
	 * update person info
	 */
	@GetMapping("/personInfo")
	public String goPersonInfo(User user,HttpServletRequest request, Model model){
		
		return "module/personInfo";        	
	}
	@PostMapping("/personInfo/update")
	public String updatePersonInfo(User user,HttpServletRequest request, Model model){
		User curUser=(User) request.getSession(false).getAttribute(ConstantUtil.nameOfCurUser);
		if(user.getName()!=null&&!"".equals(user.getName().trim()))
			curUser.setName(user.getName());
		if(user.getPhone()!=null&&!"".equals(user.getPhone().trim()))
			curUser.setPhone(user.getPhone());
		if(user.getAddress()!=null&&!"".equals(user.getAddress().trim()))
			curUser.setAddress(user.getAddress());
		customerService.updatePersonInfo(user);
		return "module/personInfo";        	
	}
	@PostMapping("/password/update")
	public String updatePassword(String oldPassword,String newPassword,HttpServletRequest request, Model model){
		User curUser=(User) request.getSession(false).getAttribute(ConstantUtil.nameOfCurUser);
		String message="update password fail. your old password was not right";
		if(oldPassword.equals(curUser.getPassword())){
			curUser.setPassword(newPassword);
			customerService.updatePersonInfo(curUser);
			message="update password successful";
		}
		model.addAttribute("message", message);
		return "module/personInfo";        	
	}
	
	
	
	
	/*
	 * Order Details
	 * Order Status (Processing Order -> Preparing for Shipment->Shipped->Complete)
	 */
	
	/*
	 * Comment Product (Only Purchased)
	 */
	
	/*
	 * View Buy History (Daily /Weekly/ Monthly/ Yearly)- Search
	 */
	
	
}